﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Helper
{
    /// <summary>
    /// Zip助手类
    /// </summary>
    public class ZipHelper
    {
        //参考文档：https://github.com/icsharpcode/SharpZipLib/wiki/FastZip

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="zipFilePath">压缩文件的路径</param>
        /// <param name="targetDir">解压的目录</param>
        /// <param name="fileFilter">文件筛选，正则表达式</param>
        /// <returns></returns>
        public static ReturnResultInfo FastZipiUnpack(string zipFilePath,string targetDir,string? fileFilter = null)
        {
            ReturnResultInfo res = new();
            if (!File.Exists(zipFilePath))
            {
                res.SetFailure($"压缩文件:{zipFilePath}不存在，请查证！");
            }
            else
            {
                try
                {
                    FastZip fastZip = new FastZip();
                    // 如果目标文件名已经存在将总是覆盖
                    fastZip.ExtractZip(zipFilePath, targetDir, fileFilter);
                    res.SetSuccess($"文件[{zipFilePath}]已解压至：{targetDir}");
                }
                catch (Exception ex)
                {
                    res.SetException($"文件[{zipFilePath}]解压失败", ex);
                }
            }
            return res;
        }

        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="zipFilePath">压缩文件的保存路径</param>
        /// <param name="recurse">是否通过递归遍历目录结构来包含所有文件</param>
        /// <param name="sourceDir">压缩的目录</param>
        /// <param name="fileFilter">文件筛选，正则表达式</param>
        /// <returns></returns>
        public static ReturnResultInfo FastZipPack(string zipFilePath,string sourceDir,bool recurse = true, string? fileFilter = null)
        {
            ReturnResultInfo res = new();
            if (!Directory.Exists(sourceDir))
            {
                res.SetFailure($"目录:{sourceDir}不存在，请查证！");
            }
            else
            {
                try
                {
                    FastZip fastZip = new FastZip();
                    fastZip.CreateZip(zipFilePath, sourceDir, recurse, fileFilter);
                    res.SetSuccess($"目录[{sourceDir}]已压缩至：{zipFilePath}");
                }
                catch (Exception ex)
                {
                    res.SetException($"目录[{sourceDir}]压缩失败", ex);
                }
            }
            return res;
        }
    }
}
